package unicall.unicom.uniwell;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import cn.ekuma.android.shard.R;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

public class UpdateManager {

	private Context mContext;

	// 提示语
	private String updateMsg = "有最新的软件包，是否升级？";
	private String version;

	// 返回的安装包url
	private String apkUrl = "";
	private Dialog noticeDialog;

	private Dialog downloadDialog;
	/* 下载包安装路径 */
	private String savePath = "/sdcard/mobiletiketingupdate/";
	//private String dataPath ;
	String path = "";
	private String saveFileName = "";

	/* 进度条与通知ui刷新的handler和msg常量 */
	private ProgressBar mProgress;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

    HashMap<String, String> mHashMap=null;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			path = savePath;
			saveFileName = savePath + "android_update.apk";
		} else {
			path = context.getFilesDir().getName();
			saveFileName = "android_update.apk";
			//lhjtianji dataPath = savePath;
			//saveFileName = dataPath + "shaolin_android_position.apk";
		}
		// savePath=Environment.getExternalStorageDirectory()+"/mobiletiketingupdate/";
		// UpdateRelease.apk
	}
	
	

	// 外部接口让主Activity调用
	public void checkUpdateInfo(String versionfile) {
		System.out .println("UPDATEmanager---93-------检查升级:"+versionfile);
		if (isUpdate(versionfile)) {
			showNoticeDialog();
		}
	}

    /**
     * 检查软件是否有更新版本
     * @return
     */
    private boolean isUpdate(String versionfile) {
        URL url;//定义网络中version.xml的连接
        InputStream inStream;
        try { //一个测试
            url = new URL(versionfile);//创建version.xml的连接地址。
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            inStream = connection.getInputStream();//从输入流获取数据
        }
        catch (Exception e) {
            e.printStackTrace();//测试失败
            return false;
        }

        // 解析XML文件。 由于XML文件比较小，因此使用DOM方式进行解析
        ParseXmlService service = new ParseXmlService();

        try {
            mHashMap = service.parseXml(inStream);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);

        if(null != mHashMap) {
            int serviceCode = Integer.valueOf(mHashMap.get("versionCode"));
            apkUrl=mHashMap.get("downloadURL");
            updateMsg=mHashMap.get("displayMessage");
            //版本判断
            if(serviceCode > versionCode) {
                return true;
            }
            showNoUpdateDialog();
        }
        return false;
    }


    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context)
    {
        int versionCode = 0;
        try
        {
            // 获取软件版本号，
            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionCode;
    }


    private void showNoUpdateDialog(){
        Builder builder = new Builder(mContext);
        builder.setTitle("更新提示");
        builder.setMessage("以是最新软件版本，无须更新，请以后在试");
        builder.setNegativeButton("完成", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showNoticeDialog() {
		Builder builder = new Builder(mContext);
		builder.setTitle("软件版本更新");
		builder.setMessage(updateMsg);
		builder.setPositiveButton("下载", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton("以后再说", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		noticeDialog = builder.create();
		noticeDialog.show();
	}

	private void showDownloadDialog() {
		Builder builder = new Builder(mContext);
		builder.setTitle("软件版本更新");

		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				interceptFlag = true;
			}
		});
		downloadDialog = builder.create();
		downloadDialog.show();

		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				System.out
						.println("UpdateManager--------------171---------开始下载");
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				if(!Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)){
					System.out.println("246---------------no sd ka-----");
					 FileOutputStream outStream = mContext.openFileOutput(saveFileName , Context.MODE_WORLD_READABLE);
					 int count = 0;
				        if (is != null) {
				            byte[] buf = new byte[1024];
				          do {
				        	  	int ch = 0;
				            	ch = is.read(buf);
				                count += ch;	
				                progress = (int) (((float) count / length) * 100);
								// 更新进度
								mHandler.sendEmptyMessage(DOWN_UPDATE);
								if (ch <= 0) {
									// 下载完成通知安装
									System.out
											.println("UpdateManager---------------------199--------下载完成----");
									mHandler.sendEmptyMessage(DOWN_OVER);
									break;
								}
								 outStream.write(buf,0,ch);
				        }while(!interceptFlag);
				    }
				                 
				        outStream.flush();
				        if (outStream != null) {
				            outStream.close();
				        }
				        if (is != null) {
				            is.close();
				        } 
				}
				else{
				File file = new File(path);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);
				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						System.out
								.println("UpdateManager---------------------199--------下载完成----");
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	};

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param url
	 */
	private void installApk() {
		File apkfile;
		
		if(!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)){
			System.out.println("updatemanager-------------335--------begin 安装");
			apkfile = new File(mContext.getFilesDir().getName()+saveFileName);
			if (!apkfile.exists()) {
				return;
			}
			System.out
					.println("UpdateManaget-----------------------236--------安装APK--------");
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");
			mContext.startActivity(i);
			
		}
		else{
		apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		System.out
				.println("UpdateManaget-----------------------236--------安装APK--------");
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);
		}
	}
}